<?php

namespace app\common\services;

use app\common\facade\Log;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Vod\V20180717\Models\SearchMediaRequest;
use TencentCloud\Vod\V20180717\VodClient;

class TencentCloudService
{
    /**
     * @var string
     */
    protected $ak;

    /**
     * @var string
     */
    protected $sk;

    /**
     * @var string
     */
    protected $domain;

    /**
     * @var string
     */
    protected $pullDomain;

    /**
     * @var string
     */
    protected $appName;

    /**
     * @var string
     */
    protected $subAppId;

    public function __construct()
    {
        // 腾讯牛云配置信息
        $this->ak          = env('tencentcloud.ak');
        $this->sk          = env('tencentcloud.sk');
        $this->domain      = env('tencentcloud.domain');
        $this->pullDomain  = env('tencentcloud.pullDomain');
        $this->appName     = env('tencentcloud.appName');
        $this->subAppId     = env('tencentcloud.subAppId');
    }


    /**
     * 搜索媒体信息
     * @param string $stream
     * @return false|mixed|string
     */
    public function getLiveSearchMedia(string $stream = '',$createTimeRange = [])
    {
        // 设置默认时区为 'Asia/Shanghai'（北京时间）
        date_default_timezone_set('Asia/Shanghai');
        // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
        // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
        // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
        $cred = new Credential($this->ak, $this->sk);
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("vod.tencentcloudapi.com");

        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        // 实例化要请求产品的client对象,clientProfile是可选的
        $client = new VodClient($cred, "", $clientProfile);

        $createTimeRangeData = [];
        if (!empty($createTimeRange)) {
            list($startTime,$endTime) = $createTimeRange;
            // 'c' 是 ISO 8601 格式的格式字符
            $startTime = gmdate("Y-m-d\TH:i:s\Z", $startTime);
            $endTime = gmdate("Y-m-d\TH:i:s\Z", $endTime+30);

            $createTimeRangeData = [
                'StartTime' => $startTime,
                'EndTime' => $endTime
            ];
        }

        try {
            // 实例化一个请求对象,每个接口都会对应一个request对象
            $req = new SearchMediaRequest();

            $params = array(
                "SubAppId" => (int)$this->subAppId,
                "StreamIds" => array($stream),
                "Categories" => array( "Video" ),
                'Filters' => [
                    'basicInfo'
                ]
            );
            if (!empty($createTimeRangeData)){
                $params = array_merge($params,$createTimeRangeData);
            }
            Log::info('腾讯云=>调用【搜索媒体信息】接口，params信息：' . json_encode($params));
            $req->fromJsonString(json_encode($params));

            // 返回的resp是一个SearchMediaResponse的实例，与请求对象对应
            $resp = $client->SearchMedia($req);
            $data = json_decode($resp->toJsonString(), true);
            if ($data == null || empty($data) || isset($data['Response']['Error'])) {
                Log::info('腾讯云=>调用【搜索媒体信息】接口，Err信息：' . json_encode($data));
                return [];
            }
            Log::info('腾讯云=>调用【搜索媒体信息】接口, Sucess信息：' . json_encode($data));
            $mediaInfoSet = $data['MediaInfoSet'] ?? [];
            return $mediaInfoSet;
        }catch (\Throwable $e){
            Log::info('腾讯云=>调用【查询流状态】接口，Err信息：' . json_encode([
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]));
            return [];
        }
    }

    public function getLiveMediaUrl(string $stream = '',$createTimeRange = [])
    {
        $mediaInfoSet = $this->getLiveSearchMedia($stream,$createTimeRange);
        if (empty($mediaInfoSet)) return $mediaInfoSet;
        $urlList = array_column(array_column($mediaInfoSet,'BasicInfo'),'MediaUrl');
        Log::info('getLiveMediaUrl=>调用【搜索媒体信息】接口, 直播回放地址数组：' . json_encode($urlList));
        return $urlList;
    }
}